package cn.lblbc.countdown

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import kotlin.math.min

class CircularProgressView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val progressPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val backgroundPaint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val progressRect = RectF()
    private var maxProgress = 100f
    private var currentProgress = 0f
    private var strokeWidth = 20f

    init {
        initPaints()
    }

    private fun initPaints() {
        // 背景圆环画笔
        backgroundPaint.apply {
            color = Color.parseColor("#E0E0E0") // 浅灰色
            style = Paint.Style.STROKE
            strokeCap = Paint.Cap.ROUND
            this.strokeWidth = this@CircularProgressView.strokeWidth
        }

        // 进度圆弧画笔
        progressPaint.apply {
            color = Color.parseColor("#2196F3") // 蓝色主题色
            style = Paint.Style.STROKE
            strokeCap = Paint.Cap.ROUND
            this.strokeWidth = this@CircularProgressView.strokeWidth
        }
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        val padding = strokeWidth / 2
        progressRect.set(
            padding,
            padding,
            w - padding,
            h - padding
        )
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)

        // 绘制背景圆环
        canvas.drawOval(progressRect, backgroundPaint)

        // 绘制进度圆弧
        val sweepAngle = 360 * currentProgress / maxProgress
        canvas.drawArc(progressRect, -90f, sweepAngle, false, progressPaint)
    }

    fun setProgress(progress: Float) {
        currentProgress = progress.coerceIn(0f, maxProgress)
        invalidate()
    }

    fun setMaxProgress(max: Float) {
        maxProgress = max
    }

    fun setStrokeWidth(width: Float) {
        strokeWidth = width
        progressPaint.strokeWidth = width
        backgroundPaint.strokeWidth = width
        invalidate()
    }
}